<template>
    <div class="container">
        <div class="search-content">
        <el-form :model="searchContent" ref="searchFrom" :inline="true">
            <el-form-item label="活动时间：">
                <el-date-picker
                    v-model="groupTime"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期" 
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="['00:00:00', '23:59:59']"
                    @change="handleChangeTime">
                </el-date-picker>
            </el-form-item>
            <el-form-item prop="store_name" label="所属店铺：">
                <el-input v-model="searchContent.store_name" placeholder="所属店铺" maxlength="32"></el-input>
            </el-form-item>
            <el-form-item prop="status" label="活动状态：">
                <el-select v-model="searchContent.status" placeholder="请选择状态">
                    <el-option
                        v-for="item in statusType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="group_title" label="团购名称：">
                <el-input v-model="searchContent.group_title" placeholder="团购名称" maxlength="32"></el-input>
            </el-form-item>
            <el-form-item prop="group_id" label="团购ID：">
                <el-input v-model="searchContent.group_id" placeholder="团购ID" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button type="primary" @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>
        </div>
        <div class="search-list">
            <el-table 
                border :data="dataList" :height="oHeight" ref="tableRef"
                :default-sort="defaultSort" @sort-change="handleSortChange">
                <el-table-column label="团购ID" width="80" align="center" prop="ncgb_id"></el-table-column>
                <el-table-column label="团购名称" min-width="140" align="center" show-overflow-tooltip prop="ncgb_title_name">
                </el-table-column>
                <el-table-column align="center" prop="ncgb_store_name" show-overflow-tooltip label="所属店铺" min-width="140">
				</el-table-column>
                <el-table-column align="center" label="活动时间" show-overflow-tooltip min-width="210">
                    <template #default="{row}">
                        {{ getActiveDate(row) }}
                    </template>
                </el-table-column>
                <el-table-column label="访问人数" min-width="100" align="center" prop="visitor_num" sortable="custom">
                </el-table-column>
                <el-table-column label="报名量" min-width="90" align="center" prop="join_num" sortable="custom"></el-table-column>
                <el-table-column label="转化率" min-width="70" align="center" prop="conversion" :formatter="getPercentage">
                </el-table-column>
                <el-table-column label="平均访问次数" width="100" align="center" prop="number"></el-table-column>
                <el-table-column label="主动分享人数" min-width="120" align="center" prop="share_num"></el-table-column>
                <el-table-column label="触发分享率" min-width="100" align="center" prop="trigger_share_rate" :formatter="getPercentage">
                </el-table-column>
                <el-table-column label="着陆分享率" min-width="100" align="center" prop="share_rate" :formatter="getPercentage">
                </el-table-column>
                <el-table-column label="集客率" min-width="70" align="center" prop="target_ratio" :formatter="getPercentage">
                </el-table-column>
                <el-table-column label="定金" min-width="80" align="center" prop="ncgb_intention_gold" show-overflow-tooltip></el-table-column>
                <el-table-column label="品线名称" min-width="140" align="center" prop="parent_depart_name" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属集团" min-width="140" align="center" prop="first_depart_name" show-overflow-tooltip></el-table-column>
                <el-table-column label="活动短链" min-width="100" align="center">
                    <template #default="{row}">
                        <el-button type="primary" @click="handleShoreLink(row)">
                            复制
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="活动详情" min-width="180" align="center">
                    <template #default="{row}">
                        <el-button 
                            type="primary" 
                            @click="handleDetail(row)">
                            查看
                        </el-button>
                        <el-button 
                            type="primary" 
                            @click="analyse(row)">
                            复盘心得
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog
  title="提示"
  :visible.sync="analyseVisible"
  width="50%"
 >
 <el-input
  type="textarea"
  placeholder="请输入内容"
  v-model="analyseInfo"
  maxlength="300"
  show-word-limit
  :autosize="{ minRows: 5}"
>
</el-input>
  <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="saveAnalyse">保 存</el-button>
  </span>
</el-dialog>
        </div>
        <div class="bottom flex-item">
            <div class="btn-group">
				<el-button type="primary" @click="getData('export')">导出检索数据</el-button>
            </div>
            <div class="paginationOne">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageParams.curpage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageParams.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageParams.total">
                </el-pagination>
            </div>
        </div>
        <group-detail type="newCar" :options="detailOptions" :groupBrandList="groupBrandList" />
        <short-link type="newcar" :options="shortLinkOptions" />
    </div>
</template>
<script>
import { resize } from "@/common/js/height.js"
import { objScreen, dateFormatter } from "@/common/js/util.js"
import GroupDetail from './group-detail.vue'
import ShortLink from './short-link.vue'
import Qs from 'qs'
export default {
    components: { GroupDetail, ShortLink },
    data() {
        return {
            searchContent: {
                start_time: '',       // 开始时间
                end_time: '',         // 结束时间 
                group_id: '',         // 团购ID
				group_title: '',      // 团购名称
				store_name: '',       // 店铺名称
                status: '',           // 活动状态
                is_search: false      // 是否处于搜索
            },
			groupTime: '',            // 活动时间 [start, end]
            statusType: [             // 活动状态
				// {label: '全部', value: 0},
				{label: '已开启', value: 4},
				{label: '已结束', value: 0}
            ],
            pageParams: {
                curpage: 1,           // 当前页码
                pageSize: localStorage.getItem('pageSize') * 1 || 10,
                total: 0              // 数据总数
            },
            dataList: [],             // 列表数据
            defaultSort: {},          // 表格排序
            sortOrder: {
                descending: "desc",
                ascending: 'asc'
            },
            oHeight: 600,             // 默认高度, 其值会在mounted中的resize进行重新计算
            groupBrandList: [],       // 品牌列表
            detailOptions: {          // 团购详情组件参数
                visible: false 
            },
            shortLinkOptions: {       // 短链生成dialog参数           
                visible: false,       
                row: {}
            },
            analyseVisible:false,
            analyseInfo:"",
            analyseID:"",
        }
    },
    methods: {
        analyse(row){
            this.analyseID = row.ncgb_id;
            this.$http.get(`/admin/newCarGroupBuy/index.php?act=groupBuy&op=getExperience&id=${row.ncgb_id}`).then(res=>{
                if(res.code == 1){
                    this.analyseInfo = res.data.info
                    this.analyseVisible = true;
                }else {
                    this.$message.warning(res.msg)
                }
            })
        },
        saveAnalyse(){
            this.$http.post('/admin/newCarGroupBuy/index.php?act=groupBuy&op=setExperience',{id:this.analyseID,experience:this.analyseInfo}).then(res=>{
                if(res.code == 1){
                    this.$message.success(res.msg)
                    this.analyseVisible = false;
                }else {
                    this.$message.warning(res.msg)
                }
            })
        },
        handleChangeTime(val) {
            if(val) {
                this.searchContent.start_time = val[0]
                this.searchContent.end_time = val[1]
            } else {
                this.searchContent.start_time = null
                this.searchContent.end_time = null
            }
        },
		getNewCarGroupBrandList() {
            const datas = { pid: 1, type: 'father' }
			this.$http.post('/admin/newCarGroupBuy/index.php?act=groupBuy&op=getChildBrand', datas)
            .then(res => {
				if (res.code == 1) {
					this.groupBrandList = res?.data.map(item => {
						return {
							brand_id: item.brand_id,
							brand_name: item.brand_name
						}
					})
				} else {
                    throw res.msg
				}
			})
            .catch(error => {
                error && this.$message.error(`${error}`)
            })
		},
        async getData(action = null) {
            let datas = {
                pageSize: this.pageParams.pageSize,
                page: this.pageParams.curpage
            }
            const { prop, order } = this.defaultSort
            if (prop && order) {
                datas = { ...datas, order_field: prop, order_sort: this.sortOrder[order] }
            }
            if (this.searchContent.is_search) {
                datas = {...datas, ...this.searchContent}
            }
            datas = objScreen(datas)
            const apiUrl = '/admin/newCarGroupBuy/index.php?act=groupBuy&op=statisticsList'
            if (action === "export") {
                datas.export = 1
                let domain = document.domain
				if (domain != 'admin.mycjj.com' && domain != 'admin.chejj.cn') {
					domain = 'admin.chejj.cn'
				}
				const url = location.protocol + 
                    '//' + domain.replace('admin', 'api') + 
                    `${apiUrl}&` + 
                    Qs.stringify(datas)
                window.open(url)
            } else {
                return this.$http.get(apiUrl, { params: datas })
                .then(res => {
                    if (res.code == 1) {
                        const pagePrefix = 'pages/newCarGroup/newCarGroupdetail/newCarGroupdetail'
                        this.dataList = res.data?.list.map(item => {
                            item.link = pagePrefix + '?store_id='+ item.ncgb_store_id +'&group_id=' + item.ncgb_id
                            return item
                        }) || []
						this.pageParams.total = +res.data.totalNum
                    } else {
                        throw res.msg
                    }
                })
                .catch(error => {
                    error && this.$message.error(`${error}`)
                })
            }
        },
        handleSortChange({column, prop, order}) {
            this.defaultSort = { prop, order }
            this.handleSearch()
        },
        handleSizeChange(pageSize) {
            localStorage.setItem('pageSize', pageSize)
			this.pageParams.pageSize = pageSize
			this.pageParams.curpage = 1
			this.getData();
        },
        handleCurrentChange(page) {
			this.pageParams.curpage = page
			this.getData()
        },
        handleSearch() {
            if(!this.searchContent.is_search) this.searchContent.is_search = true
            this.pageParams.curpage = 1
            this.getData()
        },
        handleReset() {
            this.groupTime = null
            this.$refs.searchFrom.resetFields()
            if(!this.searchContent.is_search) return
            this.searchContent = {
                is_search: false
            }
            this.defaultSort = {}
            this.$refs['tableRef'].clearSort()
            this.pageParams.curpage = 1
            this.getData()
        },
        getActiveDate(row) {
            const { ncgb_start_time, ncgb_end_time } = row
            const diffDay = Math.floor((+new Date(ncgb_end_time) - +new Date(ncgb_start_time)) / 86400000)
            return `
                ${dateFormatter("YYYY-MM-DD", ncgb_start_time)} 至 
                ${dateFormatter("YYYY-MM-DD", ncgb_end_time)} 
                (${diffDay})`
        },
        handleShoreLink(row) {
            this.shortLinkOptions = { visible: true, row }
        },
        handleDetail({ ncgb_id }) {
            this.detailOptions = { visible: true, groupId: +ncgb_id }
        },
        getPercentage(row, column, value) {
            return Math.round(value * 10**4) / 100 + '%'
        }
    },
    created() {
        this.getNewCarGroupBrandList()
        this.getData()
    },
	mounted() {
		resize(this)
	}
}
</script>